package org.grayrabbit.cms.util;

import java.io.InputStream;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.handsome.ip.IPSeeker;

public class IpUtil {

	private static final String ipFile;
	private static final String ipPath;
	protected final static Logger LOG = LoggerFactory.getLogger(IpUtil.class);
	
	public static String getClientIp(HttpServletRequest request) {
	       String ip = request.getHeader("x-forwarded-for");
	       if(LOG.isDebugEnabled()) {
	    	   LOG.debug("x-forwarded-for = {}", ip);
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getHeader("Proxy-Client-IP");
	           if(LOG.isDebugEnabled()) {
		    	   LOG.debug("Proxy-Client-IP = {}", ip);
		       }
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getHeader("WL-Proxy-Client-IP");
	           if(LOG.isDebugEnabled()) {
		    	   LOG.debug("WL-Proxy-Client-IP = {}", ip);
		       }
	       }
	       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	           ip = request.getRemoteAddr();
	           if(LOG.isDebugEnabled()) {
		    	   LOG.debug("RemoteAddr-IP = {}", ip);
		       }
	       }
	       if(StringUtils.isNotBlank(ip)) {
	    	   ip = ip.split(",")[0];
	       }
	       return ip;
	   }
	
	public static String getIpLoaction(String ip){
		IPSeeker ips=new IPSeeker(ipFile,ipPath); 
		//获得地区
		String address = ips.getIPLocation(ip).getCountry();
		String area = ips.getIPLocation(ip).getArea();
		return address + " " + area;
	}
	
	static{
		Properties prop = new Properties();
		try {
			InputStream stream = IpUtil.class.getResourceAsStream("/application.properties");
			prop.load(stream);
		} catch (Exception e) {
		}
		ipFile  = prop.getProperty("ipFile", "QQWry.Dat");
		ipPath = prop.getProperty("ipPath", "");
	}
	
//	public  static void main(String[] args){
//		 System.out.println(IpUtil.getIpLoaction("58.62.226.211"));
//	 }
}
